package com.ujiuye.controller;

import com.ujiuye.pojo.Employee;
import com.ujiuye.pojo.User;
import com.ujiuye.service.EmployeeService;
import com.ujiuye.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/login")
    public String doLogin(Employee employee, Model model, String code){
        System.out.println("login");
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            return "success";
        }
        UsernamePasswordToken token = new UsernamePasswordToken
                (employee.getUsername(), employee.getPassword().toCharArray(), null);
        token.setRememberMe(true);
        //shiro登录验证
        try {
            subject.login(token);
            return "success";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return "fail";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return "fail";
        } catch (AuthenticationException e){
            e.printStackTrace();
            return "fail";
        } catch (Exception e){
            return "fail";
        }
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        request.getSession().setAttribute("LOGIN_SESSION",null);
        if (subject != null) {
            try{
                subject.logout();
            }catch(Exception ex){
            }
        }
        response.sendRedirect("/login.html");
    }

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "/unauthorized.html";
    }
}
